// 学院课程页面JavaScript功能

// 检查是否在学院课程页面
if (window.location.pathname.includes('academy-courses.html')) {

// 课程数据 - 精简后保留每个分类的代表性视频
const coursesData = [
    // 金融服务专题 - 保留1个
    {
        id: 1,
        title: "现场培训视频-发展中企业股权融资思路",
        category: "金融服务",
        videoUrl: "https://cfcall.oss-cn-shenzhen.aliyuncs.com/flieName/现场培训视频-发展中企业股权融资思路.mp4",
        thumbnail: "https://cfcall.oss-cn-shenzhen.aliyuncs.com/20241203/d33d6d49d422465bbb9d1056016f7629.png",
        views: 104,
        rating: 4.5,
        ratingCount: 15,
        description: "详细讲解发展中企业股权融资的策略思路和实施方案",
        createTime: "2024-12-03"
    },
    // 创始人分享专题 - 保留3个
    {
        id: 11,
        title: "创始人带你走进金顾云",
        category: "创始人分享",
        videoUrl: "https://cfcall.oss-cn-shenzhen.aliyuncs.com/flieName/%E5%8F%B6%E5%89%91%E7%94%9F-%E5%88%9B%E5%A7%8B%E4%BA%BA%E5%B8%A6%E4%BD%A0%E8%B5%B0%E8%BF%9B%E9%87%91%E9%A1%BE%E4%BA%91.mp4_20250102_22074910_20250102_22262083_20250102_22404878.mp4",
        thumbnail: "https://cfcall.oss-cn-shenzhen.aliyuncs.com/20250102/7c5f1ff3b1f44bb49ee16f114351b870.png",
        views: 267,
        rating: 4.8,
        ratingCount: 38,
        description: "创始人叶剑生亲自介绍金顾云的发展历程、企业文化和未来愿景",
        createTime: "2025-01-02"
    },
    {
        id: 12,
        title: "金顾云的价值观",
        category: "创始人分享",
        videoUrl: "https://cfcall.oss-cn-shenzhen.aliyuncs.com/flieName/金顾云的价值观_20250223_17394255.mp4",
        thumbnail: "",
        views: 304,
        rating: 4.7,
        ratingCount: 42,
        description: "创始人深度阐述金顾云的核心价值观和企业理念",
        createTime: "2025-02-23"
    },
    {
        id: 13,
        title: "金顾云的优势",
        category: "创始人分享",
        videoUrl: "https://cfcall.oss-cn-shenzhen.aliyuncs.com/flieName/金顾云的优势_20250223_17365804.mp4",
        thumbnail: "",
        views: 295,
        rating: 4.6,
        ratingCount: 39,
        description: "创始人分析金顾云在行业中的核心优势和竞争力",
        createTime: "2025-02-23"
    },
    // 合伙人专区 - 保留1个
    {
        id: 14,
        title: "miniCFC信托融资知识精讲",
        category: "合伙人专区",
        videoUrl: "https://cfcall.oss-cn-shenzhen.aliyuncs.com/flieName/信托融资预告.mp4",
        thumbnail: "",
        views: 246,
        rating: 4.5,
        ratingCount: 35,
        description: "信托融资知识的深度精讲，涵盖信托产品结构和操作要点",
        createTime: "2025-06-10"
    },
    // 思享会 - 保留1个
    {
        id: 19,
        title: "新公司法时代下，创业者要做的8个调整——范否",
        category: "思享会",
        videoUrl: "https://cfcall.oss-cn-shenzhen.aliyuncs.com/flieName/范否_20250223_18210067_20250223_19072488.mp4",
        thumbnail: "https://cfcall.oss-cn-shenzhen.aliyuncs.com/20250223/353c068a732a404090170f7bd53916fe.jpg",
        views: 238,
        rating: 4.6,
        ratingCount: 34,
        description: "新公司法时代下，创业者需要做出的8个重要调整，范否老师深度解读",
        createTime: "2025-02-23"
    },
    // 企服公开会 - 保留1个
    {
        id: 25,
        title: "财务数据提升企业竞争力",
        category: "企服公开会",
        videoUrl: "https://cfcall.oss-cn-shenzhen.aliyuncs.com/flieName/5月14日(5).mp4",
        thumbnail: "",
        views: 162,
        rating: 4.3,
        ratingCount: 23,
        description: "深入分析如何通过财务数据优化提升企业核心竞争力",
        createTime: "2025-05-16"
    },
    // 融资相关 - 保留1个
    {
        id: 26,
        title: "信托计划",
        category: "融资相关",
        videoUrl: "https://cfcall.oss-cn-shenzhen.aliyuncs.com/flieName/信托计划培训.mp4",
        thumbnail: "",
        views: 247,
        rating: 4.3,
        ratingCount: 32,
        description: "详细介绍信托计划的基本概念、运作模式和实际应用",
        createTime: "2025-01-02"
    },
    // 营销相关 - 保留1个
    {
        id: 30,
        title: "常年融资顾问服务如何助力企业发展",
        category: "营销相关",
        videoUrl: "https://cfcall.oss-cn-shenzhen.aliyuncs.com/flieName/常年融资顾问服务如何助力企业发展.mp4",
        thumbnail: "",
        views: 359,
        rating: 4.5,
        ratingCount: 48,
        description: "深入解析常年融资顾问服务的核心价值和企业发展助力作用",
        createTime: "2025-01-02"
    }
];

// 评论数据（模拟）
const commentsData = {
    1: [
        {
            id: 1,
            author: "张三",
            content: "课程内容很实用，对我的工作帮助很大！讲解清晰易懂",
            time: "2024-01-16 10:30"
        },
        {
            id: 2,
            author: "李四",
            content: "讲解很清晰，推荐给同事们学习",
            time: "2024-01-17 14:20"
        }
    ],
    2: [
        {
            id: 3,
            author: "王五",
            content: "对金融行业的分析很到位，学到了很多",
            time: "2024-01-21 09:15"
        }
    ]
};

// 全局变量
let currentPage = 1;
let currentCategory = 'all';
let searchQuery = '';
let filteredCourses = [];
let currentCourse = null;
let userRatings = {}; // 用户评分记录
let videoTimeLimit = 180; // 3分钟 = 180秒
let formSubmitted = false; // 表单是否已提交
let timeLimitNotice = null; // 倒计时提示元素

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializePage();
    bindEvents();
});

// 初始化页面
function initializePage() {
    filteredCourses = coursesData;
    updateStats();
    renderCourses();
    renderPagination();
}

// 绑定事件
function bindEvents() {
    // 搜索功能
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');
    
    if (searchInput) {
        searchInput.addEventListener('input', debounce(handleSearch, 300));
    }
    if (searchBtn) {
        searchBtn.addEventListener('click', handleSearch);
    }
    
    // 筛选功能
    const filterBtns = document.querySelectorAll('.filter-btn');
    filterBtns.forEach(btn => {
        btn.addEventListener('click', handleFilter);
    });
    
    // 视频模态框
    const videoModal = document.getElementById('videoModal');
    const closeModal = document.getElementById('closeModal');
    
    if (closeModal) {
        closeModal.addEventListener('click', closeVideoModal);
    }
    
    if (videoModal) {
        videoModal.addEventListener('click', function(e) {
            if (e.target === videoModal) {
                closeVideoModal();
            }
        });
    }
    
    // ESC键关闭模态框
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeVideoModal();
            closeFormModal();
        }
    });
    
    // 表单相关事件
    const formModal = document.getElementById('formModal');
    const closeFormBtn = document.getElementById('closeForm');
    const contactForm = document.getElementById('contactForm');
    
    if (closeFormBtn) {
        closeFormBtn.addEventListener('click', closeFormModal);
    }
    
    if (formModal) {
        formModal.addEventListener('click', function(e) {
            if (e.target === formModal) {
                closeFormModal();
            }
        });
    }
    
    if (contactForm) {
        contactForm.addEventListener('submit', handleFormSubmit);
    }
    
    // 窗口大小改变时重新渲染
    window.addEventListener('resize', debounce(function() {
        renderCourses();
        renderPagination();
    }, 300));
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 搜索处理
function handleSearch() {
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchQuery = searchInput.value.trim();
        currentPage = 1;
        filterCourses();
    }
}

// 筛选处理
function handleFilter(e) {
    const filterBtns = document.querySelectorAll('.filter-btn');
    filterBtns.forEach(btn => btn.classList.remove('active'));
    e.target.classList.add('active');
    
    currentCategory = e.target.dataset.category;
    currentPage = 1;
    filterCourses();
}

// 过滤课程
function filterCourses() {
    let courses = coursesData;
    
    // 按分类筛选
    if (currentCategory !== 'all') {
        courses = courses.filter(course => course.category === currentCategory);
    }
    
    // 按标题搜索
    if (searchQuery) {
        courses = courses.filter(course => 
            course.title.toLowerCase().includes(searchQuery.toLowerCase())
        );
    }
    
    filteredCourses = courses;
    updateStats();
    renderCourses();
    renderPagination();
}

// 更新统计信息
function updateStats() {
    const totalCourses = filteredCourses.length;
    const totalViews = filteredCourses.reduce((sum, course) => sum + course.views, 0);
    const avgRating = filteredCourses.length > 0 ? 
        (filteredCourses.reduce((sum, course) => sum + course.rating, 0) / filteredCourses.length).toFixed(1) : 0.0;
    
    const totalCoursesEl = document.getElementById('totalCourses');
    const totalViewsEl = document.getElementById('totalViews');
    const avgRatingEl = document.getElementById('avgRating');
    
    if (totalCoursesEl) totalCoursesEl.textContent = totalCourses;
    if (totalViewsEl) totalViewsEl.textContent = totalViews.toLocaleString();
    if (avgRatingEl) avgRatingEl.textContent = avgRating;
}

// 渲染课程列表
function renderCourses() {
    const courseGrid = document.getElementById('courseGrid');
    if (!courseGrid) return;
    
    // 根据屏幕宽度调整每页显示的课程数量
    const isMobile = window.innerWidth <= 768;
    const pageSize = isMobile ? 6 : 9; // 手机端显示6个，电脑端显示9个
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const currentCourses = filteredCourses.slice(startIndex, endIndex);
    
    if (currentCourses.length === 0) {
        courseGrid.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-search"></i>
                <h3>没有找到相关课程</h3>
                <p>请尝试调整搜索条件或筛选选项</p>
            </div>
        `;
        return;
    }
    
    courseGrid.innerHTML = currentCourses.map(course => `
        <div class="course-card" onclick="openVideoModal(${course.id})">
            <div class="course-thumbnail ${course.thumbnail ? 'has-image' : ''}" 
                 ${course.thumbnail ? `style="background-image: url('${course.thumbnail}')"` : ''}>
                ${!course.thumbnail ? '<i class="fas fa-play-circle"></i>' : ''}
                <div class="play-icon">
                    <i class="fas fa-play"></i>
                </div>
            </div>
            <div class="course-info">
                <div class="course-header">
                    <span class="course-category">${course.category}</span>
                </div>
                <h3 class="course-title">${course.title}</h3>
                <div class="course-meta">
                    <div class="course-rating">
                        <div class="stars">
                            ${generateStars(course.rating)}
                        </div>
                        <span class="rating-score">${course.rating}</span>
                    </div>
                    <span class="view-count">
                        <i class="fas fa-eye"></i>
                        ${course.views}
                    </span>
                </div>
            </div>
        </div>
    `).join('');
}

// 生成星级评分HTML
function generateStars(rating) {
    const fullStars = Math.floor(rating);
    const hasHalfStar = rating % 1 !== 0;
    let starsHTML = '';
    
    for (let i = 0; i < fullStars; i++) {
        starsHTML += '<i class="fas fa-star"></i>';
    }
    
    if (hasHalfStar) {
        starsHTML += '<i class="fas fa-star-half-alt"></i>';
    }
    
    const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0);
    for (let i = 0; i < emptyStars; i++) {
        starsHTML += '<i class="far fa-star"></i>';
    }
    
    return starsHTML;
}

// 渲染分页
function renderPagination() {
    const pagination = document.getElementById('pagination');
    if (!pagination) return;
    
    // 根据屏幕宽度调整每页显示的课程数量
    const isMobile = window.innerWidth <= 768;
    const pageSize = isMobile ? 6 : 9;
    const totalPages = Math.ceil(filteredCourses.length / pageSize);
    
    if (totalPages <= 1) {
        pagination.innerHTML = '';
        return;
    }
    
    let paginationHTML = '';
    
    // 上一页
    paginationHTML += `
        <button ${currentPage === 1 ? 'disabled' : ''} onclick="changePage(${currentPage - 1})">
            <i class="fas fa-chevron-left"></i>
        </button>
    `;
    
    // 页码
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);
    
    if (startPage > 1) {
        paginationHTML += `<button onclick="changePage(1)">1</button>`;
        if (startPage > 2) {
            paginationHTML += `<span>...</span>`;
        }
    }
    
    for (let i = startPage; i <= endPage; i++) {
        paginationHTML += `
            <button class="${i === currentPage ? 'active' : ''}" onclick="changePage(${i})">
                ${i}
            </button>
        `;
    }
    
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            paginationHTML += `<span>...</span>`;
        }
        paginationHTML += `<button onclick="changePage(${totalPages})">${totalPages}</button>`;
    }
    
    // 下一页
    paginationHTML += `
        <button ${currentPage === totalPages ? 'disabled' : ''} onclick="changePage(${currentPage + 1})">
            <i class="fas fa-chevron-right"></i>
        </button>
    `;
    
    pagination.innerHTML = paginationHTML;
}

// 切换页面
function changePage(page) {
    currentPage = page;
    renderCourses();
    renderPagination();
    
    // 滚动到顶部
    const mainContent = document.querySelector('.main-content');
    if (mainContent) {
        mainContent.scrollIntoView({ behavior: 'smooth' });
    }
}

// 打开视频模态框
function openVideoModal(courseId) {
    currentCourse = coursesData.find(c => c.id === courseId);
    if (!currentCourse) return;
    
    // 重置表单状态
    formSubmitted = false;
    
    const modal = document.getElementById('videoModal');
    const videoPlayer = document.getElementById('videoPlayer');
    const videoTitle = document.getElementById('videoTitle');
    const courseCategory = document.getElementById('courseCategory');
    const viewCount = document.getElementById('viewCount');
    const videoError = document.getElementById('videoError');
    
    // 设置视频信息
    if (videoTitle) videoTitle.textContent = currentCourse.title;
    if (courseCategory) courseCategory.textContent = currentCourse.category;
    if (viewCount) viewCount.textContent = `观看次数: ${currentCourse.views}`;
    
    // 隐藏错误提示
    if (videoError) {
        videoError.style.display = 'none';
    }
    
    // 设置视频源
    if (videoPlayer) {
        // 清除之前的源
        const sources = videoPlayer.querySelectorAll('source');
        sources.forEach(source => {
            source.src = '';
        });
        
        // 设置新的视频源
        const mp4Source = videoPlayer.querySelector('source[type="video/mp4"]');
        if (mp4Source) {
            mp4Source.src = currentCourse.videoUrl;
        }
        
        videoPlayer.load(); // 重新加载视频
        
        // 添加错误处理
        videoPlayer.onerror = function() {
            console.log('视频加载失败:', currentCourse.videoUrl);
            if (videoError) {
                videoError.style.display = 'block';
            }
        };
        
        // 添加加载成功处理
        videoPlayer.onloadedmetadata = function() {
            console.log('视频元数据加载成功');
            if (videoError) {
                videoError.style.display = 'none';
            }
        };
        
        // 添加播放事件监听
        videoPlayer.onplay = function() {
            console.log('视频开始播放');
            startTimeLimitMonitoring();
        };
        
        // 添加时间更新监听
        videoPlayer.ontimeupdate = function() {
            checkTimeLimit();
        };
    }
    
    // 初始化水印和安全系统
    initWatermarkSystem();
    enableVideoProtection();
    
    // 显示模态框
    if (modal) {
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
    
    // 增加观看次数（模拟）
    currentCourse.views++;
    updateStats();
    renderCourses();
}

// 重试视频加载
function retryVideo() {
    if (currentCourse) {
        const videoPlayer = document.getElementById('videoPlayer');
        const videoError = document.getElementById('videoError');
        
        if (videoError) {
            videoError.style.display = 'none';
        }
        
        if (videoPlayer) {
            videoPlayer.load();
        }
    }
}

// 关闭视频模态框
function closeVideoModal() {
    const modal = document.getElementById('videoModal');
    const videoPlayer = document.getElementById('videoPlayer');
    
    // 清理水印系统
    destroyWatermarkSystem();
    
    // 移除倒计时提示
    removeTimeLimitNotice();
    
    // 关闭表单弹窗
    closeFormModal();
    
    if (modal) {
        modal.classList.remove('active');
        document.body.style.overflow = 'auto';
    }
    
    // 停止视频播放
    if (videoPlayer) {
        videoPlayer.pause();
        videoPlayer.currentTime = 0;
    }
    
    currentCourse = null;
    formSubmitted = false;
}

// 水印系统
let watermarkTimerInterval;
let securityCheckInterval;

// 初始化水印系统
function initWatermarkSystem() {
    updateWatermarkTime();
    // 每秒更新时间戳
    watermarkTimerInterval = setInterval(updateWatermarkTime, 1000);
    
    // 启动安全监控
    startSecurityMonitoring();
}

// 更新水印时间戳
function updateWatermarkTime() {
    const watermarkTime = document.getElementById('watermarkTime');
    if (watermarkTime) {
        const now = new Date();
        const timeString = now.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
        watermarkTime.textContent = timeString;
    }
}

// 安全监控系统
function startSecurityMonitoring() {
    // 检测开发者工具
    securityCheckInterval = setInterval(() => {
        // 检测控制台是否打开
        if (window.outerHeight - window.innerHeight > 200 || 
            window.outerWidth - window.innerWidth > 200) {
            console.clear();
            console.log('%c警告！', 'color: red; font-size: 30px; font-weight: bold;');
            console.log('%c金顾云学院视频受版权保护，禁止下载和传播！', 'color: red; font-size: 16px;');
        }
    }, 1000);
}

// 基础防护措施
function enableVideoProtection() {
    const videoContainer = document.getElementById('videoContainer');
    const videoPlayer = document.getElementById('videoPlayer');
    
    if (videoContainer && videoPlayer) {
        // 禁用右键菜单
        videoContainer.addEventListener('contextmenu', function(e) {
            e.preventDefault();
            showProtectionWarning('禁止右键操作');
            return false;
        });
        
        // 禁用拖拽
        videoPlayer.addEventListener('dragstart', function(e) {
            e.preventDefault();
            return false;
        });
        
        // 禁用选择
        videoContainer.addEventListener('selectstart', function(e) {
            e.preventDefault();
            return false;
        });
        
        // 监控键盘快捷键
        document.addEventListener('keydown', function(e) {
            // 禁用F12、Ctrl+Shift+I、Ctrl+Shift+J、Ctrl+U等
            if (e.key === 'F12' || 
                (e.ctrlKey && e.shiftKey && (e.key === 'I' || e.key === 'J')) ||
                (e.ctrlKey && e.key === 'U') ||
                (e.ctrlKey && e.key === 'S')) {
                e.preventDefault();
                showProtectionWarning('禁止使用开发者工具');
                return false;
            }
        });
        
        // 禁用画中画
        videoPlayer.disablePictureInPicture = true;
        
        // 监控视频事件
        videoPlayer.addEventListener('loadedmetadata', function() {
            // 确保控制列表限制
            videoPlayer.controlsList.add('nodownload');
            videoPlayer.controlsList.add('nofullscreen');
            videoPlayer.controlsList.add('noremoteplayback');
        });
    }
}

// 显示保护警告
function showProtectionWarning(message) {
    // 创建警告提示
    const warning = document.createElement('div');
    warning.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(255, 0, 0, 0.9);
        color: white;
        padding: 20px;
        border-radius: 8px;
        z-index: 10000;
        font-size: 16px;
        font-weight: bold;
        text-align: center;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
    `;
    warning.textContent = message;
    document.body.appendChild(warning);
    
    // 3秒后移除警告
    setTimeout(() => {
        if (warning && warning.parentNode) {
            warning.parentNode.removeChild(warning);
        }
    }, 3000);
}

// 清理水印系统
function destroyWatermarkSystem() {
    if (watermarkTimerInterval) {
        clearInterval(watermarkTimerInterval);
        watermarkTimerInterval = null;
    }
    if (securityCheckInterval) {
        clearInterval(securityCheckInterval);
        securityCheckInterval = null;
    }
}

// 开始时间限制监控
function startTimeLimitMonitoring() {
    // 创建倒计时提示
    createTimeLimitNotice();
    
    // 更新倒计时显示
    updateTimeLimitNotice();
}

// 检查时间限制
function checkTimeLimit() {
    const videoPlayer = document.getElementById('videoPlayer');
    if (!videoPlayer || formSubmitted) return;
    
    const currentTime = videoPlayer.currentTime;
    const remainingTime = videoTimeLimit - currentTime;
    
    if (currentTime >= videoTimeLimit) {
        // 暂停视频
        videoPlayer.pause();
        
        // 显示表单
        showFormModal();
        
        // 移除倒计时提示
        removeTimeLimitNotice();
    } else {
        // 更新倒计时显示
        updateTimeLimitNotice(remainingTime);
    }
}

// 创建倒计时提示
function createTimeLimitNotice() {
    const modalContent = document.querySelector('.modal-content');
    if (!modalContent || timeLimitNotice) return;
    
    timeLimitNotice = document.createElement('div');
    timeLimitNotice.className = 'time-limit-notice';
    timeLimitNotice.innerHTML = '免费观看剩余时间: <span id="timeRemaining">3:00</span>';
    
    modalContent.appendChild(timeLimitNotice);
}

// 更新倒计时提示
function updateTimeLimitNotice(remainingTime) {
    if (!timeLimitNotice) return;
    
    const timeRemainingEl = timeLimitNotice.querySelector('#timeRemaining');
    if (timeRemainingEl) {
        const minutes = Math.floor(remainingTime / 60);
        const seconds = Math.floor(remainingTime % 60);
        timeRemainingEl.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
    }
}

// 移除倒计时提示
function removeTimeLimitNotice() {
    if (timeLimitNotice) {
        timeLimitNotice.remove();
        timeLimitNotice = null;
    }
}

// 显示表单弹窗
function showFormModal() {
    const formModal = document.getElementById('formModal');
    if (formModal) {
        formModal.classList.add('active');
    }
}

// 关闭表单弹窗
function closeFormModal() {
    const formModal = document.getElementById('formModal');
    if (formModal) {
        formModal.classList.remove('active');
    }
}

// 处理表单提交
function handleFormSubmit(e) {
    e.preventDefault();
    
    const formData = new FormData(e.target);
    const formObject = {};
    
    // 收集表单数据
    for (let [key, value] of formData.entries()) {
        formObject[key] = value;
    }
    
    // 验证必填字段
    const requiredFields = ['name', 'phone', 'company', 'position', 'service'];
    const missingFields = requiredFields.filter(field => !formObject[field]);
    
    if (missingFields.length > 0) {
        alert('请填写所有必填字段');
        return;
    }
    
    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(formObject.phone)) {
        alert('请输入正确的手机号码');
        return;
    }
    
    // 处理服务字段
    if (formObject.service === '其他') {
        if (!formObject.customService || formObject.customService.trim() === '') {
            alert('请填写您感兴趣的服务');
            return;
        }
        formObject.service = formObject.customService.trim();
    }
    
    // 保存表单数据到本地存储
    const submissions = JSON.parse(localStorage.getItem('videoFormSubmissions') || '[]');
    submissions.push({
        ...formObject,
        courseId: currentCourse.id,
        courseTitle: currentCourse.title,
        submitTime: new Date().toISOString()
    });
    localStorage.setItem('videoFormSubmissions', JSON.stringify(submissions));
    
    // 标记表单已提交
    formSubmitted = true;
    
    // 关闭表单弹窗
    closeFormModal();
    
    // 继续播放视频
    const videoPlayer = document.getElementById('videoPlayer');
    if (videoPlayer) {
        videoPlayer.play();
    }
    
    // 显示成功提示
    showSuccessMessage();
}

// 显示成功提示
function showSuccessMessage() {
    const successMessage = document.createElement('div');
    successMessage.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(40, 167, 69, 0.9);
        color: white;
        padding: 20px 30px;
        border-radius: 8px;
        font-size: 16px;
        font-weight: 500;
        z-index: 3000;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
    `;
    successMessage.textContent = '信息提交成功！视频将继续播放';
    document.body.appendChild(successMessage);
    
    // 3秒后移除提示
    setTimeout(() => {
        if (successMessage && successMessage.parentNode) {
            successMessage.parentNode.removeChild(successMessage);
        }
    }, 3000);
}

// 全局函数，供HTML调用
window.changePage = changePage;
window.openVideoModal = openVideoModal;
window.retryVideo = retryVideo;
window.initWatermarkSystem = initWatermarkSystem;
window.enableVideoProtection = enableVideoProtection;
window.destroyWatermarkSystem = destroyWatermarkSystem;
window.closeFormModal = closeFormModal;
window.handleServiceChange = handleServiceChange;

// 处理服务选择变化
function handleServiceChange() {
    const serviceSelect = document.getElementById('service');
    const customServiceInput = document.getElementById('customService');
    
    if (serviceSelect && customServiceInput) {
        if (serviceSelect.value === '其他') {
            customServiceInput.style.display = 'block';
            customServiceInput.required = true;
            customServiceInput.focus();
        } else {
            customServiceInput.style.display = 'none';
            customServiceInput.required = false;
            customServiceInput.value = '';
        }
    }
}

} // 结束页面检查
